package com.huaxin.hxcloud.frendcircles;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.Entity.FindInfo;
import com.huaxin.common.frendcircle.bean.CommentItem;
import com.huaxin.common.frendcircle.utils.UrlUtils;
import com.huaxin.common.frendcircle.widgets.CommentListView;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.common.view.nicegridview.NineGridImageView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ImgViewActivity;
import com.huaxin.hxcloud.find.HttpCommit;
import com.huaxin.hxcloud.find.ImgsAdapter;
import com.huaxin.hxcloud.find.SendCommentActivity;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.main.contactview.friend.FriendInfoActivity;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.model.contact.Contact;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by yiwei on 16/5/17.
 */
public class CircleAdapter extends BaseRecycleViewAdapter {


    public final static int TYPE_HEAD     = 0;
    public static final int CONTENT       = 5;
    public static final int Type_FOOTER   = 2;
    public static final int HEADVIEW_SIZE = 1;
    private CirclePresenter           presenter;
    private Context                   context;
    private FindInfo.QuestionListBean questionListBean;

    private FrendCircleActivity activity;

    public FrendCircleActivity getActivity() {
        return activity;
    }

    public void setActivity(FrendCircleActivity activity) {
        this.activity = activity;
    }

    public void setCirclePresenter(CirclePresenter presenter) {
        this.presenter = presenter;
    }

    private Activity mActivity;

    public CircleAdapter(Context context) {
        this.context = context;
        this.mActivity = (Activity) context;
    }

    public void setquestionListBean(FindInfo.QuestionListBean questionListBean) {
        this.questionListBean = questionListBean;
    }

    public FindInfo.QuestionListBean getQuestionListBean() {
        return this.questionListBean;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_HEAD;
        } else if (position == getItemCount() - 1) {
            return Type_FOOTER;
        } else {
            return CONTENT;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        if (viewType == TYPE_HEAD) {
            View headerView = LayoutInflater.from(context).inflate(R.layout.list_header_item, parent, false);
            viewHolder = new HeaderHodel(headerView);
        } else if (viewType == Type_FOOTER) {
            View view = LayoutInflater.from(context).inflate(R.layout.list_footers_item, parent, false);
            viewHolder = new FooterView(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_circle_item, parent, false);
            viewHolder = new CircleViewHolder(view);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
        //
        if (getItemViewType(position) == TYPE_HEAD) {
            HeaderHodel headerHodel = (HeaderHodel) viewHolder;
            FindInfo.QuestionListBean.Publisher publisher = questionListBean.getPublisher();

            //设置头像
            HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
            instance.setHeadImage(context, publisher.getUserImg(), publisher.getNickName(), headerHodel.circleImageView);


            //            Glide.with(context).load(publisher.getUserImg())
            //                    .error(R.color.bg_no_photo).into(headerHodel.circleImageView);
            //
            //            headerHodel.circleImageView.setOnClickListener(new View.OnClickListener() {
            //                @Override
            //                public void onClick(View v) {
            //                   // ToastUtil.showToastShort("这在CircleAdapter");
            //                }
            //            });

            headerHodel.niceName.setText(publisher.getNickName());
            headerHodel.content.setVisibility(View.VISIBLE);
            headerHodel.content.setText(questionListBean.getContent());
            String publishDate = questionListBean.getPublishDate();
            final long parseLong = Long.parseLong(publishDate);
            headerHodel.upTime.setText("" + StringUtils.friendlyTime(new Date(parseLong)));
            headerHodel.comentNum.setText("" + questionListBean.getCommentNum());
            //
            if (null != questionListBean.getImgUrls()) {
               // headerHodel.gridView.setVisibility(View.VISIBLE);
                final List<String> imgUrls = questionListBean.getImgUrls();
                headerHodel.gridView.setAdapter(new ImgsAdapter(imgUrls, context));

                headerHodel.mNineGridImg.setImagesData(imgUrls);
                NineGridImageViewAdaper adapter=new NineGridImageViewAdaper();
                headerHodel.mNineGridImg.setAdapter(adapter);
                headerHodel.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(context, ImgViewActivity.class);
                        intent.putExtra("position", position);
                        intent.putStringArrayListExtra("img", (ArrayList<String>) imgUrls);
                        context.startActivity(intent);
                    }
                });
            } else {
              //  headerHodel.gridView.setVisibility(View.GONE);
            }
            //
            headerHodel.skipLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, SendCommentActivity.class);
                    intent.putExtra("questionId", questionListBean.getQuestionId());
                    intent.putExtra("toUserId", questionListBean.getPublisher().getId());
                    context.startActivity(intent);
                }
            });
            //处理评论人头像
            List<FindInfo.LikeerArrayBean> likeerArray = questionListBean.getLikeerArray();
            if (likeerArray != null && likeerArray.size() != 0) {
                headerHodel.iconll.setVisibility(View.VISIBLE);
                RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context, 8);
                headerHodel.iconLayout.setLayoutManager(layoutManager);
                IconRecyclerAdapter adapter = new IconRecyclerAdapter(context);
                headerHodel.iconLayout.setAdapter(adapter);

                adapter.setDatas(likeerArray);
                adapter.notifyDataSetChanged();
            } else {
                headerHodel.iconll.setVisibility(View.GONE);
            }
            //
        } else if (getItemViewType(position) == Type_FOOTER) {
            final FooterView footerView = (FooterView) viewHolder;
            if (datas.size() == 0) {
                footerView.textView.setVisibility(View.VISIBLE);
            } else {
                footerView.textView.setVisibility(View.GONE);
            }
            getActivity().setSoftState(new FrendCircleActivity.OnSoftState() {
                @Override
                public void onState(boolean flags) {
                    if (datas.size() != 0) {
                        if (flags) {
                            footerView.layout.setVisibility(View.VISIBLE);
                        } else {
                            footerView.layout.setVisibility(View.GONE);
                        }
                    }
                }
            });
        } else {
            final int circlePosition = position - HEADVIEW_SIZE;//实际位置
            final CircleViewHolder holder = (CircleViewHolder) viewHolder;
            final CircleItem circleItem = (CircleItem) datas.get(circlePosition);
            final String circleId = circleItem.getId();
            final String name = circleItem.getUser().getName();
            final String headImg = circleItem.getUser().getHeadUrl();
            final String id = circleItem.getUser().getId();
            final String content = circleItem.getContent();
            String createTime = circleItem.getCreateTime();
            final List<CommentItem> commentsDatas = circleItem.getComments();
            boolean hasComment = circleItem.hasComment();


            HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
            instance.setHeadImage(context, headImg, name, holder.headIv);
            // Glide.with(context).load(headImg).error(R.color.bg_no_photo).into(holder.headIv);
            //
            holder.headIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   /* Intent intent1 = new Intent(context, FindUserActivity.class);
                    intent1.putExtra("nickName", name);
                    intent1.putExtra("icon", headImg);
                    intent1.putExtra("id", Integer.valueOf(id));
                    context.startActivity(intent1);*/
                    goToUserInfoActivity(mActivity, id);
                }
            });
            holder.nameTv.setText(name);
            holder.timeTv.setText("" + createTime);
            holder.contentTv.setText(UrlUtils.formatUrlString(content));


            holder.contentTv.setVisibility(TextUtils.isEmpty(content) ? View.GONE : View.VISIBLE);
            //
            final boolean isLike = circleItem.isLike();
            if (isLike) {
                holder.zanTv.setImageResource(R.drawable.love_selected);
            } else {
                holder.zanTv.setImageResource(R.drawable.love_normal);
            }
            holder.zanTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isLike) {
                        holder.zanTv.setImageResource(R.drawable.love_selected);
                        circleItem.setLike(false);
                    } else {
                        holder.zanTv.setImageResource(R.drawable.love_normal);
                        circleItem.setLike(true);
                    }
                    HttpCommit.commitLike2(circleItem.getParentId());
                    notifyDataSetChanged();
                }
            });
            //            //
            //            if (presenter.curUser.getId().equals(circleItem.getUser().getId())) {
            //                holder.deleteBtn.setVisibility(View.GONE);
            //            } else {
            //                holder.deleteBtn.setVisibility(View.GONE);
            //            }
            //            holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
            //                @Override
            //                public void onClick(View v) {
            //                    //删除
            //                    if (presenter != null) {
            //                        presenter.deleteCircle(circleId);
            //                    }
            //                }
            //            });
            //            if (presenter.curUser.getId().equals(circleItem.getUser().getId())) {
            //                holder.layout.setOnClickListener(new View.OnClickListener() {
            //                    @Override
            //                    public void onClick(View v) {
            //                        CircleDialog circleDialog = new CircleDialog(context, presenter, circleItem, circlePosition);
            //                        circleDialog.show();
            //                    }
            //                });
            //            }
            holder.layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CircleDialog circleDialog = new CircleDialog(context, presenter, circleItem, circlePosition);
                    circleDialog.show();
                }
            });
            //
            if (hasComment) {
                holder.commentList.setDatas(commentsDatas);
                holder.commentList.setVisibility(View.VISIBLE);

                //处理评论列表
                holder.commentList.setOnItemClickListener(new CommentListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(int commentPosition) {
                        CommentItem commentItem = commentsDatas.get(commentPosition);
                        if (CirclePresenter.curUser.getId().equals(commentItem.getUser().getId())) {//复制或者删除自己的评论

                            CommentDialog dialog = new CommentDialog(context, presenter, commentItem, circlePosition);
                            dialog.show();
                        } else {//回复别人的评论
                            if (presenter != null) {
                                CommentConfig config = new CommentConfig();
                                config.circlePosition = circlePosition;
                                config.commentPosition = commentPosition;
                                config.commentType = CommentConfig.Type.REPLY;
                                config.replyUser = commentItem.getUser();
                                presenter.showEditTextBody(config);
                            }
                        }
                    }
                });
                holder.commentList.setOnItemLongClickListener(new CommentListView.OnItemLongClickListener() {
                    @Override
                    public void onItemLongClick(int commentPosition) {
                        //长按进行复制或者删除
                        CommentItem commentItem = commentsDatas.get(commentPosition);
                        CommentDialog dialog = new CommentDialog(context, presenter, commentItem, circlePosition);
                        dialog.show();
                    }
                });
                //对回复中的人名进行监听
                holder.commentList.setOnClickSpanItem(new CommentListView.OnClickSpanItem() {
                    @Override
                    public void onClick(String textStr, String id, String iconImg) {
                        List<Contact> contacts = ContactManager.getFriendList();
                        int size = contacts.size();
                        for (int i = 0; i < size; i++) {
                            String clientId = contacts.get(i).getClientId();
                            Log.e("xxxx", "onClick: " + clientId + "---" + contacts.get(i).getNickName());
                        }
                       /* Intent intent1 = new Intent(context, FindUserActivity.class);
                        intent1.putExtra("nickName", textStr);
                        intent1.putExtra("icon", iconImg);
                        intent1.putExtra("id", id);
                        context.startActivity(intent1);*/
                        goToUserInfoActivity(mActivity, id);
                    }
                });

            } else {
                holder.commentList.setVisibility(View.GONE);
            }
            //发表评论
            holder.snsBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (presenter != null) {
                        CommentConfig config = new CommentConfig();
                        config.circlePosition = circlePosition;
                        config.commentType = CommentConfig.Type.PUBLIC;
                        presenter.showEditTextBody(config);
                    }
                }
            });


        }
    }

    /**
     * 跳转到个人中心界面
     *
     * @param userid
     */
    private void goToUserInfoActivity(Activity activity, String userid) {
        Intent intent = new Intent(activity, FriendInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(ImConstants.CLIENT_ID, userid);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public int getItemCount() {
        return datas == null ? 0 : datas.size() + 2;
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
    }


    class HeaderHodel extends RecyclerView.ViewHolder {
        @BindView(R.id.activity_find_info_icon)
        AvatarImageView circleImageView; //头像
        @BindView(R.id.activity_find_info_nice_name)
        TextView        niceName;//昵称
        @BindView(R.id.activity_find_info_time)
        TextView        upTime; //时间
        @BindView(R.id.activity_find_content_txt)
        TextView        content; //内容
        @BindView(R.id.activity_find_grid_view)
        GridView        gridView;
        @BindView(R.id.activity_find_scroll_view)
        RecyclerView    iconLayout;//评论人头像
        @BindView(R.id.activity_find_info_comment_num)
        TextView        comentNum; //评论数
        @BindView(R.id.activity_find_info_skip)
        LinearLayout    skipLayout; //评论跳转
        @BindView(R.id.activity_find_icon_ll)
        LinearLayout    iconll;
        @BindView(R.id.ninegrid_img)
        NineGridImageView mNineGridImg;

        public HeaderHodel(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class FooterView extends RecyclerView.ViewHolder {
        @BindView(R.id.adpater_footer_item)
        TextView     textView;
        @BindView(R.id.adpater_footer_ll)
        LinearLayout layout;

        public FooterView(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
